<?php
namespace Modules\News\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Modules\Base\Entities\Basereply;
use Modules\News\Entities\Newsreply;
use Modules\News\Http\Requests\NewsreplyRequest;
use Modules\Wachat\Entities\Wxrule;

class NewsreplyController extends Controller
{
    //显示列表
    public function index()
    {
        $data = Newsreply::paginate(10);
        return view('news::newsreply.index', compact('data'));
    }

    //创建视图
    public function create(Newsreply $newsreply,WechatService $wechatService)
    {
        $view = $wechatService->rule();
        return view('news::newsreply.create',compact('newsreply','view'));
    }

    //保存数据
    public function store(NewsreplyRequest $request,Newsreply $newsreply,WechatService $wechatService)
    {
        //调用服务类方法处理规则和关键词
        $rule = $wechatService->SaveRule();
        //添加回复内容
        Newsreply::create([
            'data' => $request->input('data'),
            'rule_id' => $rule['id'],
        ]);
        return redirect('/news/newsreply')->with('success', '保存成功');
    }

    //显示记录
    public function show(Newsreply $field)
    {
        return view('news::newsreply.show', compact('field'));
    }

    //编辑视图
    public function edit(Newsreply $newsreply,WechatService $wechatService)
    {
        $view = $wechatService->rule($newsreply['rule_id']);
        return view('news::newsreply.edit', compact('newsreply','view'));
    }

    //更新数据
    public function update(NewsreplyRequest $request, Newsreply $newsreply,WechatService $wechatService)
    {
        //将规则数据和关键词数据调用服务类方法进行保存
        $rule = $wechatService->saveRule($newsreply['rule_id']);
        //对图文回复数据进行编辑
        $newsreply->data = $request->input('data');
        $newsreply->rule_id = $rule['id'];
        $newsreply->save();
        return redirect('/news/newsreply')->with('success','更新成功');
    }

    //删除模型
    public function destroy(Newsreply $newsreply)
    {
        //删除对应规则数据
        Wxrule::destroy($newsreply['rule_id']);
        $newsreply->delete();
        return redirect('news/newsreply')->with('success','删除成功');
    }
}
